package com.hzit.web.test;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class Dom4j01 {


    public static void main(String[] args) throws DocumentException, IOException {

        //1.获取document对象

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("F:\\IdeaProjects\\bj2004\\weixin-parent\\weixin-web\\src\\main\\java\\com\\hzit\\web\\test\\student.xml"));
        System.out.println(document);

        //2.遍历对象的内容
        Element root = document.getRootElement();

        //3.遍历所有子节点
        List<Element> elements = root.elements();

        for (Element element : elements) {
            //获取属性
            String attr = element.attributeValue("grade");
            System.out.println("attr:" + attr);

            List<Element> elements1 = element.elements();
            for (Element element1 : elements1) {
                System.out.println("\t\t"+element1.getName()+"-"+element1.getStringValue());
            }

            //现在地址
            Element addElement = element.addElement("班级");
            addElement.setText("BJ2004");


        }



        OutputFormat format= OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8"); //指定XML编码
        XMLWriter writer=new XMLWriter(new FileWriter("F:\\output.xml"),format);
        writer.write(document);
        writer.close();

    }

}
